package lapsnake.model.data;

import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.Iterator;

import lapsnake.model.LapNode;

public class ChildList<T extends LapNode> extends AbstractChildField<T> implements Iterable<T>
{
	private boolean optional;
	
	private ArrayList<T> list;
	
	public ChildList(LapNode owner, Class<T> childType, boolean optional)
	{
		this(owner, childType, optional, true);
	}

	public ChildList(LapNode owner, Class<T> childType, boolean optional, boolean indented)
	{
		super(owner, childType, indented);
		this.optional = optional;
		list = new ArrayList<>();
	}

	@Override
	public int indexOf(LapNode n)
	{
		return list.indexOf(n);
	}
	@Override
	public boolean isOptional()
	{
		return optional;
	}

	@Override
	public boolean isList()
	{
		return true;
	}

	@Override
	public int size()
	{
		return list.size();
	}

	@Override
	public T get(int index)
	{
		return list.get(index);
	}

	@Override
	public void set(int index, T child, Object exclude, boolean fireEvents)
		throws IllegalArgumentException, PropertyVetoException
	{
		checkVetos(exclude, child);
		if(index == list.size())
			list.add(child);
		else
			list.set(index, child);
		if(fireEvents)
			fireEvents(exclude);
	}

	@Override
	public void remove(Object exclude, boolean fireEvents) throws IllegalArgumentException, PropertyVetoException
	{
		checkVetos(exclude, null);
		if(list.size() == 1 && !optional)
			throw new IllegalArgumentException(this+" is not an optional field... Cannot remove the last element!"); 
		T rem = list.remove(list.size()-1);
		assert rem != null;
		if(fireEvents)
			fireEvents(exclude);
	}

	@Override
	public Iterator<T> iterator()
	{
		return list.iterator();
	}	
	@Override
	public String toString()
	{
		return "List of "+type.getSimpleName()+'('+size()+") on "+getOwner();
	}
}
